<template>
  <ContentWrap class="mobile-container">
    <!--    顶部查询项-->
    <el-form :model="form" inline label-width="70px" class="mobile-form">
      <el-form-item label="状态">
        <el-select v-model="form.status" clearable placeholder="请选择状态" style="width: 200px">
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="退款方式">
        <el-select
          v-model="form.transfer_type"
          clearable
          placeholder="请选择退款方式"
          style="width: 200px"
        >
          <el-option
            v-for="item in transferTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">查询</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 移动端卡片视图 -->
    <div v-if="isMobile" class="mobile-card">
      <el-card v-for="item in dataList" :key="item.id" class="fund-return-card">
        <template #header>
          <div class="card-header">
            <span class="order-id">序号: {{ item.id }}</span>
            <el-tag :type="getStatusTagType(item.status)" size="small">
              {{ useEnumeratePicker(statusList, item.status) }}
            </el-tag>
          </div>
        </template>

        <div class="card-content">
          <div class="info-row">
            <span class="label">退款方式:</span>
            <span class="value">{{
              useEnumeratePicker(transferTypeList, item.transfer_type)
            }}</span>
          </div>

          <div class="info-row">
            <span class="label">支付时间:</span>
            <span class="value">{{ item.pay_time || '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">应付金额:</span>
            <span class="value">{{ item.pay_amount ?? item.total_amount ?? '-' }}</span>
          </div>

          <div class="info-row">
            <span class="label">已付金额:</span>
            <span class="value">{{ item.paid_amount || '-' }}</span>
          </div>
        </div>

        <!-- 移动端操作按钮 -->
        <div class="card-actions">
          <el-button
            v-if="item.status !== '01'"
            type="primary"
            size="small"
            @click="openUpload(item)"
            class="action-btn"
          >
            上传退款凭证
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 桌面端表格视图 -->
    <div v-else class="mobile-table">
      <el-table
        :data="dataList"
        highlight-current-row
        stripe
        border
        v-loading="tableLoading"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <!-- 序号 -->
        <el-table-column label="序号" width="70">
          <template #default="{ row }">
            {{ row.id }}
          </template>
        </el-table-column>

        <!-- 退货退款单编号 -->
        <el-table-column
          :label="t('orderReturn.returnorder_no')"
          prop="returnorder_no"
          min-width="180"
          :show-overflow-tooltip="true"
        />

        <!-- 订单编号 -->
        <el-table-column
          :label="t('order.orderCode')"
          prop="order_no"
          min-width="160"
          :show-overflow-tooltip="true"
        />

        <!-- 订单序号 -->
        <el-table-column
          :label="t('order.order_id')"
          prop="order_id"
          min-width="120"
          :show-overflow-tooltip="true"
        />

        <!-- 退款方式 -->
        <el-table-column label="退款方式" min-width="180" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ useEnumeratePicker(transferTypeList, row.transfer_type) }}
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" min-width="120" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ useEnumeratePicker(statusList, row.status) }}
          </template>
        </el-table-column>

        <!-- 支付时间 -->
        <el-table-column
          label="支付时间"
          prop="pay_time"
          min-width="180"
          :show-overflow-tooltip="true"
        />

        <!-- 应付金额 -->
        <el-table-column label="应付金额" min-width="160" :show-overflow-tooltip="true">
          <template #default="{ row }">
            {{ row.pay_amount ?? row.total_amount ?? '' }}
          </template>
        </el-table-column>

        <!-- 已付金额 -->
        <el-table-column
          label="已付金额"
          prop="paid_amount"
          min-width="160"
          :show-overflow-tooltip="true"
        />

        <!-- 操作 -->
        <el-table-column label="操作" min-width="160" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status !== '01'"
              size="small"
              type="primary"
              @click="openUpload(row)"
              >上传退款凭证</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--    分页-->
    <Pagination
      class="mobile-table"
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
  </ContentWrap>

  <DialogUpload ref="DialogUploadRef" @refresh="initialize" class="mobile-dialog" />
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { getEnumApi, getRefundOrderListApi, getOrderPaymentResourceApi } from '@/api/orderReturn'
import { ElButton, ElMessage } from 'element-plus'
import { useClipboard } from '@vueuse/core'
import DialogUpload from '@/views/OrderReturn/OrderReturnManage/components/DialogUpload/index.vue'
import { useAppStore } from '@/store/modules/app'

const { copy } = useClipboard()
const { t } = useI18n()
const { push } = useRouter()
const appStore = useAppStore()

// 移动端检测
const isMobile = computed(() => appStore.getMobile)

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const multipleSelection = ref<any[]>([])
const DialogUploadRef = ref()

// 获取状态标签类型
const getStatusTagType = (status: string | number) => {
  switch (status) {
    case '01':
      return 'success' // 已完成
    case '00':
      return 'warning' // 待处理
    default:
      return 'info'
  }
}

const openUpload = (row: any) => {
  nextTick(() => {
    DialogUploadRef!.value!.dialogVisible = true
    DialogUploadRef!.value!.getBackShow(row, 1) // 传递 type 参数，1 表示订单费用
  })
}

const paginationTotal = ref<number>(0)
const form = ref<Record<string, any>>({
  status: '',
  transfer_type: '',
  pageIndex: 1,
  pageSize: 20
})

const modelList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])
const returnorderTypeList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])
const transferTypeList = ref<Array<Record<string, any>>>([])

//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  modelList.value = resp.data.model
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
  returnorderTypeList.value = resp.data.returnorder_type
  orderTypeList.value = resp.data.order_type
}

// 获取支付资源枚举（含 transfer_type 和 pay_status）
const getPaymentResource = async () => {
  const resp = await getOrderPaymentResourceApi()
  transferTypeList.value = resp?.data?.transfer_type || []
  // 尝试获取 status 或 pay_status
  statusList.value = resp?.data?.status || resp?.data?.pay_status || []
}

//根据接口枚举匹配出中文名称
const useEnumeratePicker = (
  enumList: any[],
  field: string | number,
  key?: string,
  value?: string
) => {
  if (!enumList) return
  const matchItem =
    enumList.find((item: Record<string, any>) => item[value ?? 'value'] === field) || {}
  return matchItem[key ?? 'label'] || ''
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getRefundOrderListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    status: '',
    transfer_type: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

onMounted(() => {
  getDropDownBoxInfo()
  getPaymentResource()
  initialize()
})
</script>

<style lang="less" scoped>
// 覆盖全局移动端样式
@media (width <= 768px) {
  .mobile-form .el-button {
    display: flex !important;
    margin-bottom: 0 !important;
    justify-content: center !important;
  }
}

// 移动端卡片样式优化
.mobile-card {
  .fund-return-card {
    .el-card__body {
      padding: 16px;

      .info-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
        line-height: 1.5;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          min-width: 90px;
          margin-right: 8px;
          font-weight: 500;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          line-height: 1.4;
          color: #333;
          text-align: right;
          word-break: break-all;
          flex: 1;
        }
      }
    }

    .el-card__header {
      padding: 12px 16px;

      .card-header {
        display: flex;
        font-size: 14px;
        font-weight: 600;
        justify-content: space-between;
        align-items: center;

        .order-id {
          font-size: 14px;
          font-weight: 600;
        }

        .el-tag {
          font-size: 12px;
        }
      }
    }

    .card-actions {
      display: flex;
      padding-top: 16px;
      margin-top: 16px;
      border-top: 1px solid #f0f0f0;
      flex-direction: column;
      gap: 8px;
    }
  }
}
</style>
